//
//  DBJPersonInfoTableViewController.m
//  DBJ
//
//  Created by 花化华 on 2016/11/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "DBJPersonInfoTableViewController.h"
#import "DBJUserDefaultsTool.h"
#import "DBJLoginModel.h"
#import <Masonry.h>
#import "DBJPersonInfoCell.h"
#import "DBJPersonFootView.h"



static NSString *IconCell = @"IconCell";

@interface DBJPersonInfoTableViewController ()

@property (nonatomic,strong) DBJPersonFootView * footView;

@end

@interface DBJPersonInfoTableViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

/** 模型数组 */
@property(nonatomic,strong)NSMutableArray  *arrList;

//模态View
@property(nonatomic,strong)UIView  *modealView;
//数据
@property(nonatomic,copy)NSString *label;

//数据2
@property(nonatomic,copy)NSString *city;

//UItableView
@property(nonatomic,weak)UITableView  *tabView;

//相应的行和组
@property(nonatomic,assign)NSInteger  section;
@property(nonatomic,assign)NSInteger  row;
//小头像
@property(nonatomic,strong)UIButton *icon;

//当前用户的模型
@property (nonatomic,strong)DBJLoginModel *model;

@end

@implementation DBJPersonInfoTableViewController

- (void)dbjSetupSubviews{
    [super dbjSetupSubviews];

    //初始化UI
    [self setupUI];
    
    //加载数据
    [self loadData];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   
    //发送更新leftBar信息
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATELEFTINFO" object:nil userInfo:nil];
    
}

#pragma mark-初始化UI
-(void)setupUI{
    //添加一个全屏tableView
    UITableView  *tab = [[ UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    //中间修改信息视图
    self.tabView = tab;
    //注册
    [tab registerClass:[DBJPersonInfoCell class] forCellReuseIdentifier:IconCell];
    
    tab.delegate = self;
    tab.dataSource = self;
    
    [self.view addSubview:tab];
    
    //创建TableView的headView
    UIImageView *headView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1429862008539"]];
    headView.userInteractionEnabled = YES;
    
    //添加头部视图
    tab.tableHeaderView = headView;
    
    //中间的小头像
    UIButton *iconBtn = [[UIButton alloc]init];
    iconBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    iconBtn.layer.borderWidth = 2;
    iconBtn.layer.cornerRadius = 35;
    iconBtn.clipsToBounds  = YES;
    self.icon = iconBtn;
    
    //设置中间头像
    //获取本地存储的头像
    UIImage *image;
    NSString *name = [DBJUserDefaultsTool objetForKey:CURRENTID];
    NSData *iconData = [DBJUserDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-ICON",name]];
    UIImage *iconImage = [UIImage imageWithData:iconData];
    
    if (iconImage) {
        image = iconImage;
    }else{
        image = [UIImage imageNamed:@"doctor_defaultphoto_male"];
    }
    
    [iconBtn setBackgroundImage:image forState:UIControlStateNormal];
    //小头像的点击事件
    [iconBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [headView addSubview:iconBtn];
    
    iconBtn.userInteractionEnabled = YES;
    //大小
    CGFloat margin =70;
    [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(headView);
        //        make.bottom.mas_equalTo(headView.mas_bottom).offset(margin);
        make.centerY.equalTo(headView.mas_bottom).mas_offset(-10);
        make.size.mas_equalTo(CGSizeMake(margin, margin));
        
    }];
    
    //弹出视图
    DBJPersonFootView * footView = [[DBJPersonFootView alloc]init];
    _footView = footView;
    
    //记录
    self.modealView = footView;
    [self.view addSubview:footView];
    
    [footView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(250);
        make.bottom.mas_equalTo(self.view).offset(250);
    }];
}

#pragma mark-UItableViewDatasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrList.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *model = _arrList[indexPath.row];
    
    DBJPersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:IconCell forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    //为CELL赋值
    cell.inFoModel = model;
    
    //创建代码块
    void(^labelBlock)() = ^(NSString *label){
        self.label = label;
    };
    //传递代码块
    cell.labelBlock = labelBlock;
    
    return cell;
}

//选中不同cell的事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.section = indexPath.section;
    self.row = indexPath.row;
    switch (indexPath.row) {
        case 0:{
            //修改姓名
        [self updateCellWith:@"姓名"];
        }
            break;
        case 1:{
            //修改年龄
        [self updateCellWith:@"年龄"];
        }
            break;
        case 2:{
            //修改性别
        [self updateCellWith:@"性别"];
        }
            break;
        case 3:{
            //修改身高
         [self updateCellWith:@"身高"];
        }
            break;
        case 4:{
            //修改体重
        [self updateCellWith:@"体重"];
        }
            break;
        case 5:{
            //修改籍贯
            //修改常居地
            [self updateNative];
        }
            break;
        case 6:{
            //修改常居地
            [self updateNative];
        }
            break;
        case 7:{
            //修改联系方式
          [self updateCellWith:@"联系方式"];
        }
            
            break;
        case 8:{
            
            //修改证件号码
         [self updateCellWith:@"证件号码"];
        }
            
            break;

        default:
            break;
    }
    
}

/** 修改籍贯／常居地的方法 */
- (void)updateNative{
    [self.modealView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.mas_equalTo(self.view);
        
    }];
    
    //创建代码块
    void(^labelBlock)() = ^(NSString *label){
        
        NSDictionary *model = _arrList[self.row];
        NSDictionary *newModel = @{[model allKeys].lastObject : label};
        
        NSString *key = [newModel allKeys].lastObject;
        id value = [NSString stringWithFormat:@"%@",newModel[key]];
        [self updateInfo:value];
        [_arrList replaceObjectAtIndex:self.row withObject:newModel];
        
        //3.刷新tableView
        NSIndexPath *idxPath = [NSIndexPath indexPathForRow:self.row inSection:0];
        //局部刷新,刷新指定的行
        [self.tabView  reloadRowsAtIndexPaths:@[idxPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        //4.更新modealView的frame
        [self.modealView mas_updateConstraints:^(MASConstraintMaker *make) {
            
            make.bottom.mas_equalTo(self.view).offset(250);
            
        }];
        
        [UIView  animateWithDuration:0.25 animations:^{
            [self.modealView layoutIfNeeded];
        }];
        
    };
    //传递代码块
    _footView.labelBlock =labelBlock;
}

/** 修改个人信息的方法 */
- (void)updateCellWith:(NSString*)title {
    //创建一个对话框
    UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    
    //修改UIAlertView样式，显示出一个文本框
    alterView.alertViewStyle = UIAlertViewStylePlainTextInput;
    
    //获取UIAlertView的指定文本框，并且设置内容文字
    [alterView textFieldAtIndex:0].text = self.label;
    
   // NSLog(@"%@",self.label);
    //显示
    [alterView show];

}

#pragma mark - UIAlertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    //点击确定时
    if (buttonIndex == 1) {
        //更新数据
        //1.获取文本框当前内容
        NSString *text = [alertView textFieldAtIndex:0].text;
        
//        NSLog(@"%@",text);
        //2.修改当前选中的模型
        NSDictionary *model = _arrList[self.row];
        NSDictionary *newModel = @{[model allKeys].lastObject : text};
        
        NSString *key = [newModel allKeys].lastObject;
        id value = [NSString stringWithFormat:@"%@",newModel[key]];
        [self updateInfo:value];
        
        [_arrList replaceObjectAtIndex:self.row withObject:newModel];
        
        //3.刷新tableView
        NSIndexPath *idxPath = [NSIndexPath indexPathForRow:self.row inSection:0];
        //局部刷新,刷新指定的行
        [self.tabView  reloadRowsAtIndexPaths:@[idxPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

#pragma mark - 暴力更新本地数据
- (void)updateInfo:(id)value{
    //暴力修改
    switch (self.row) {
        case 0:
            _model.true_name = value;
            break;
            
        case 1:
            _model.age = value;
            break;
            
        case 2:
            _model.dbj_gender = value;
            break;
            
        case 3:
            _model.height = value;
            break;
            
        case 4:
            _model.weight = value;
            break;
            
        case 5:
            _model.address = value;
            break;
            
        case 6:
            _model.habitual_residence = value;
            break;
            
        case 7:
            _model.mobile_number = value;
            break;
            
        case 8:
            _model.card_number = value;
            break;
            
        default:
            break;
    }
    
    [DBJTools updateCurrentIDModel:_model];
}

//中间头像的点击事件
//点击头像进入相册
-(void)clickBtn:(UIButton *)sender{
    //创建图片选择器
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    //指定源的类型
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    imagePicker.allowsEditing = YES;
    
    imagePicker.delegate = self;
    
    //设置完iamgePicker后，就可以启动了。用以下方法将图像选取器的视图“推”出来
    [self presentModalViewController:imagePicker animated:YES];

    
    
}

/** 用户点击图像选取器中的“cancel”按钮时被调用，这说明用户想要中止选取图像的操作 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

/** 用户点击选取器中的“choose”按钮时被调用，告知委托对象，选取操作已经完成，同时将返回选取图片的实例 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self.icon setImage:image forState:UIControlStateNormal];
    
    NSData *data = UIImagePNGRepresentation(image);
    [DBJUserDefaultsTool saveObject:data forKey:[NSString stringWithFormat:@"%@-ICON",[DBJUserDefaultsTool objetForKey:CURRENTID]]];
    
    //发送更新leftBar个人信息的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATELEFTINFO1" object:nil userInfo:nil];
    
    
//    [self.icon.imageView setImage:image];
    [picker dismissModalViewControllerAnimated:YES];
}

/**
 * 加载数据
 */
- (void)loadData{
    //加载用户数据model
    NSString *name = [DBJUserDefaultsTool objetForKey:CURRENTID];
    NSData *modelData = [DBJUserDefaultsTool objetForKey:[NSString stringWithFormat:@"%@-MODEL",name]];
    DBJLoginModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];
    _model = model;
    
    //创建模型数组
    _arrList = [NSMutableArray arrayWithObjects:@{@"姓名" : model.true_name},@{@"年龄":model.age},@{@"性别":model.dbj_gender},@{@"身高":model.height},@{@"体重":model.weight},@{@"籍贯":model.address},@{@"常居地":model.habitual_residence},@{@"联系方式":model.mobile_number},@{@"证件号码":model.card_number}, nil];
}
/** 设置分组style的头间隔 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

@end
